package top.birdhk.TestAPI.state;

import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
import top.birdhk.TestAPI.beans.SensorReading;

/**
 * 键值状态使用例子
 */
public class StateTest_KeyedStateApplicationCase {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

//        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 定义一个flatMap操作,检测温度跳转，输出报警
        SingleOutputStreamOperator<Tuple3<String, Double, Double>> mapStream = inputStream.keyBy("id")
                .flatMap(new TempChangeWarning(10.0));


        mapStream.print("count:");

        env.execute();


    }


    public static class TempChangeWarning extends RichFlatMapFunction<SensorReading, Tuple3<String, Double, Double>> {

        // 当前温度跳变的阈值
        private Double threshold;


        public TempChangeWarning(Double threshold) {
            this.threshold = threshold;
        }

        // 定义状态，保存上一次的温度值
        private ValueState<Double> lastTemplate;

        @Override
        public void flatMap(SensorReading sensorReading, Collector<Tuple3<String, Double, Double>> collector) throws Exception {


            // 获取上一次温度值
            Double lastTemp = lastTemplate.value();


            // 如果状态不为null，就判断两次温度差值
            if (lastTemp != null){
                Double diff = Math.abs(sensorReading.getTemperature() - lastTemp);
                if (diff >= threshold){
                    collector.collect(new Tuple3<>(sensorReading.getId(),lastTemp,sensorReading.getTemperature()));
                }
            }

            // 更新状态
            lastTemplate.update(sensorReading.getTemperature());

        }

        @Override
        public void close() throws Exception {
            lastTemplate.clear();
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            lastTemplate = getRuntimeContext().getState(new ValueStateDescriptor<Double>("lastTemp",Double.class));
        }
    }



}
